package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"sailing-islanddd/cache"
	"sailing-islanddd/model"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	name := c.PostForm("name")
	like_count, _ := strconv.Atoi(c.PostForm("like_count"))
	types := c.PostForm("types")
	data := model.App{
		Name:      name,
		LikeCount: like_count,
		Types:     types,
	}
	err := model.DB.Create(&data).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}

	redis_key := "app_add_"
	var app model.App
	model.DB.Where("id = ?", data.ID).Find(&app)
	jsonData, _ := json.Marshal(app)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return
}

func List(c *gin.Context) {
	var app []model.App
	redis_key := "app_list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Find(&app)
		jsonData, _ := json.Marshal(app)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &app)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "获取成功",
		"data": app,
	})
	return
}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var app []model.App
	model.DB.Where("id = ?", id).First(&app)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "获取成功",
		"data": app,
	})
	return
}
